//
//  DataCategoryUpload.m
//  Kaagad Peso
//
//  Created by ZhengChengFeng on 2024/10/16.
//

#import "DataCategoryUpload.h"

static NSString *notReachable = @"notReachable";

@implementation DataCategoryUpload

#pragma mark -----uploadDataLocation-----
+ (void)uploadDataLocation{
    if (![AuthorHelper determineWhetherTheAPPOpensTheLocation]) {
        return;
    }
    
    NSMutableDictionary *muDic = @{
        @"murderers":PMStringIsEmpty([DKCore sharedDKCore].ISOcountryCodeStr) ? @"":esString([DKCore sharedDKCore].ISOcountryCodeStr),
        @"punish":PMStringIsEmpty([DKCore sharedDKCore].countryStr) ? @"":esString([DKCore sharedDKCore].countryStr),
        @"learn":PMStringIsEmpty([DKCore sharedDKCore].localityStr) ? @"":esString([DKCore sharedDKCore].localityStr),
        @"russian":PMStringIsEmpty([DKCore sharedDKCore].subLocalityStr) ? @"":esString([DKCore sharedDKCore].subLocalityStr),
        @"cambrian":PMStringIsEmpty([DKCore sharedDKCore].thoroughfareStr) ? @"":esString([DKCore sharedDKCore].thoroughfareStr),
        @"santo":PMStringIsEmpty([DKCore sharedDKCore].latitudeStr) ? @"":esString([DKCore sharedDKCore].latitudeStr),
        @"vila":PMStringIsEmpty([DKCore sharedDKCore].longitudeStr) ? @"":esString([DKCore sharedDKCore].longitudeStr),
        @"lewes":@"lewesLocation",
    }.mutableCopy;
    [HttpNetHelper postNetworkHelperForPath:kUploadLocationDataUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            return;
        }
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        
    } withIsForm:YES];
   
}


#pragma mark -----uploadDataIDFA-----
+ (void)uploadDataIDFA:(BOOL)isFromLogin{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self initIDFA:isFromLogin];
    });
        
}

+ (void)initIDFA:(BOOL)isFromLogin{
    
    if (@available(iOS 14,*)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            NSString *idfaStr = @"";
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                idfaStr = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
            }
            [self uploadIDFAData:idfaStr withIsFrom:isFromLogin];
        }];
        
    }
    else {
    
        NSString *idfaStr = @"";
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            idfaStr = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
        }
        [self uploadIDFAData:idfaStr withIsFrom:isFromLogin];

    }
    
}

+ (void)uploadIDFAData:(NSString *)idfaStr withIsFrom:(BOOL)isFromLogin{
    
    if (isFromLogin) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:kLoginIDFA]) {
            return;
        }
    }
    else{
        if ([[NSUserDefaults standardUserDefaults] boolForKey:kHomeIDFA]) {
            return;
        }
    }
    
    
    
    NSMutableDictionary *muDic = @{
        @"engage":@"engageGoogle",
        @"sweep":esString([IDFVTools getIDFV]),
        @"lured":esString(idfaStr),
    }.mutableCopy;
    [HttpNetHelper postNetworkHelperForPath:kUploadIDFADataUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            return;
        }
        
        if (isFromLogin) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kLoginIDFA];
        } else {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kHomeIDFA];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        
    } withIsForm:YES];
}

#pragma mark ------uploadDataDeviceInfo------------
+ (void)uploadDataDeviceInfo{
        
    NSInteger int1 = (NSInteger)[self getUseStoreMemory];
    NSInteger int2 = (NSInteger)[self getAllStoreMemory];
    NSInteger int3 = (NSInteger)[self availableMemory];
    NSInteger int4 = (NSInteger)[UIScreen mainScreen].bounds.size.height;
    NSInteger int5 = (NSInteger)[UIScreen mainScreen].bounds.size.width;
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    NSString *idfaStr = esString([ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString);
    NSMutableDictionary *muDic = @{
        
        @"woods":@"woodsDevice",
        
        @"baby":@{
            @"burned":@(int1),
            @"news":@(int2),
            @"previously":[NSString stringWithFormat:@"%ld",[[self getTotalMemory] integerValue]],
            @"binu":@(int3),
        },
        
        @"thirsty":@{
            @"reared":[NSString stringWithFormat:@"%.1lf%@",[UIDevice currentDevice].batteryLevel*100,@"%"],
            @"literally":[UIDevice currentDevice].batteryState == UIDeviceBatteryStateCharging ? @"1":@"0",
            @"artificial":@"artificialBattery",
        },
        
        @"prodigious":@{
            @"towed":@"iPhone",
            @"stunned":@(int4),
            @"sniders":@(int5),
            @"spears":[NSString stringWithFormat:@"%.1lf",[self getDeviceSize]],
            @"dose":[UIDevice currentDevice].name,
            @"langa":[UIDevice currentDevice].systemVersion,
        },
        
        @"leaping":@{
            @"flash":@"100",
            @"explosion":@"0",
            @"dynamite":[self isSimulator] ? @"1":@"0",
            @"stick":[self isYY] ? @"1":@"0",
            @"ignited":@"ignitedLeaping",
        },
        
        @"fuse":@{
            @"closer":[NSTimeZone localTimeZone].name,
            @"islets":[self isOpenProxy] ? @"1":@"0",
            @"craving":[self isOpenVPN] ? @"1":@"0",
            @"vessels":[self getOperatorName],
            @"sweep":esString([IDFVTools getIDFV]),
            @"winchester":[self getDeviceLanguage],
            @"dynamiting":[self getNetworkType],
            @"lurking":@"1",
            @"rare": [self getIPAddress],
            @"lured":PMStringIsEmpty(idfaStr) ? @"" : idfaStr,
            @"johnny":@"johnnyFuse",
            @"enfield":@"enfieldFuse",
        },
        
        @"recruited":@{
            
            @"resulted":@[
                @{
                    @"desiring":PMStringIsEmpty([[self getWIFIDict] valueForKey:@"SSID"]) ? @"":[[self getWIFIDict] valueForKey:@"SSID"],
                    @"hydrogen":PMStringIsEmpty([[self getWIFIDict] valueForKey:@"SSID"]) ? @"":[[self getWIFIDict] valueForKey:@"SSID"],
                    @"recruit":PMStringIsEmpty([[self getWIFIDict] valueForKey:@"BSSID"]) ? @"":[[self getWIFIDict] valueForKey:@"BSSID"],
                    @"customary":PMStringIsEmpty([[self getWIFIDict] valueForKey:@"BSSID"]) ? @"":[[self getWIFIDict] valueForKey:@"BSSID"],
                    @"labour":@"labourRecruited",
                },
            ],
            
        },
        
    }.mutableCopy;

    
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:muDic options:0 error:&error];
    NSString *base64String = [[jsonData base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSMutableDictionary *upDic = @{
        @"clip":base64String,
    }.mutableCopy;


    [HttpNetHelper postNetworkHelperForPath:kUploadDeviceDataUrl parameter:upDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            return;
        }
       
    } onCompleteFailur:^(NSError * _Nonnull error) {
        
    } withIsForm:YES];
   
}

+ (CGFloat)getAllStoreMemory{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSNumber *fileSystemSize = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil][NSFileSystemSize];
    unsigned long long totalSize = [fileSystemSize unsignedLongLongValue];
    
    return totalSize;

}
+ (CGFloat)getUseStoreMemory{
    NSFileManager *fileManager = [NSFileManager defaultManager];
     
    NSNumber *freeFileSystemSize = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil][NSFileSystemFreeSize];
    unsigned long long freeSize = [freeFileSystemSize unsignedLongLongValue];

    return freeSize;

}
 
+ (NSString *)getTotalMemory {
   
    int mib[2] = {CTL_HW, HW_MEMSIZE};
    uint64_t mem;
    size_t mem_size = sizeof(mem);
 
    
    if (sysctl(mib, 2, &mem, &mem_size, NULL, 0) == -1) {
        return @"0";
    }
 
    unsigned long long result = mem;
    NSString *memorySize;
    
    if (result >= (1024ULL * 1024ULL * 1024ULL)) {
        memorySize = [NSString stringWithFormat:@"%.1f", ((double)result)];
    } else if (result >= (1024ULL * 1024ULL)) {
        memorySize = [NSString stringWithFormat:@"%.1f", ((double)result)];
    } else if (result >= 1024ULL) {
        memorySize = [NSString stringWithFormat:@"%.1f", ((double)result)];
    } else {
        memorySize = [NSString stringWithFormat:@"%llu", result];
    }
 
    return memorySize;
}

+ (double)availableMemory{
  vm_statistics_data_t vmStats;
  mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
  kern_return_t kernReturn = host_statistics(mach_host_self(),
                                             HOST_VM_INFO,
                                             (host_info_t)&vmStats,
                                             &infoCount);
  
  if (kernReturn != KERN_SUCCESS) {
    return NSNotFound;
  }
    return vm_page_size *vmStats.free_count;
}


+ (NSString *)getOperatorName{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = nil;
    NSString *radioType = nil;
    
    if (info && [info respondsToSelector:@selector(serviceSubscriberCellularProviders)]) {
        NSDictionary *dic = [info serviceSubscriberCellularProviders];
        if (dic.allKeys.count) {
            carrier = [dic objectForKey:dic.allKeys[0]];
        }
    }
    
    if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
        NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
        if (radioDic.allKeys.count) {
            radioType = [radioDic objectForKey:radioDic.allKeys[0]];
        }
    }
    return PMStringIsEmpty(carrier.carrierName) ? @"":esString(carrier.carrierName);
}

+ (NSString *)getNetworkType{
    
    struct sockaddr_storage zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    
    if (!didRetrieveFlags) {
        return notReachable;
    }
    
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    if (isReachable && !needsConnection) { }else{
        return notReachable;
    }
    
    
    if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired ) {
        
        return notReachable;
        
    } else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
        
        return [self cellularType];
        
    } else {
        return @"WiFi";
    }
    
}

+ (NSString *)cellularType{
    
    CTTelephonyNetworkInfo * info = [[CTTelephonyNetworkInfo alloc] init];
    
    NSString *currentRadioAccessTechnology;
    if (@available(iOS 12.1, *)) {
        if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
            NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
            if (radioDic.allKeys.count) {
                currentRadioAccessTechnology = [radioDic objectForKey:radioDic.allKeys[0]];
            } else {
                return notReachable;
            }
        } else {
            
            return notReachable;
        }
        
    } else {
        
        currentRadioAccessTechnology = info.currentRadioAccessTechnology;
    }
    
    if (currentRadioAccessTechnology) {
        
        if (@available(iOS 14.1, *)) {
            
            if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyNRNSA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyNR]) {
                
                return @"5G";
                
            }
        }
        
        if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
            
            return @"4G";
            
        } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) {
            
            return @"3G";
            
        } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
            
            return @"2G";
            
        } else {
            
            return @"Unknow";
        }
        
        
    } else {
        
        return notReachable;
    }
}




+ (BOOL)isYY{
    BOOL status = NO;
    status = [[NSFileManager defaultManager] fileExistsAtPath:@"User/Applications"];
    if (status) {
        return YES;
    }
    return NO;
}

+ (BOOL)isOpenProxy{
    NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"https://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSDictionary *settings = proxies[0];
    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
        return NO;
    }
    return YES;
    
}

+ (BOOL)isOpenVPN{
    BOOL flag = NO;
    NSDictionary *dict = CFBridgingRelease(CFNetworkCopySystemProxySettings());
    NSArray *keys = [dict[@"__SCOPED__"] allKeys];
    for (NSString *key in keys) {
        if ([key rangeOfString:@"tap"].location != NSNotFound ||
            [key rangeOfString:@"tun"].location != NSNotFound ||
            [key rangeOfString:@"ipsec"].location != NSNotFound ||
            [key rangeOfString:@"ppp"].location != NSNotFound){
            flag = YES;
            break;
            
        }
    }
    return flag;
}
 
+ (BOOL)isSimulator {
    return TARGET_IPHONE_SIMULATOR;
}

+ (NSString *)getIPAddress{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    success = getifaddrs(&interfaces);
    if (success == 0) {
       
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                   
                    struct sockaddr_in *sa = (struct sockaddr_in *)temp_addr->ifa_addr;
                    address = [NSString stringWithUTF8String:inet_ntoa(sa->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
   
    freeifaddrs(interfaces);
    return address;
}
 
+ (CGFloat)getDeviceSize{
    
    if (kScreenHeight == 568 ) {
        return 4;
    }
    else if (kScreenHeight == 667 ) {
        return 4.7;
    }
    else if (kScreenHeight == 736 ) {
        return 5.5;
    }
    else if (kScreenHeight == 812 ) {
        return 5.8;
    }
    else if (kScreenHeight == 896 ) {
        return 6.5;
    }
    else if (kScreenHeight == 780 ) {
        return 5.4;
    }
    else if (kScreenHeight == 844 || kScreenHeight == 852 ) {
        return 6.1;
    }
    else if (kScreenHeight == 926 || kScreenHeight == 932 ) {
        return 6.7;
    }
    else if (kScreenHeight == 874 ) {
        return 6.3;
    }
    else if (kScreenHeight == 956 ) {
        return 6.9;
    }

    CGSize devicePhysicalSize = [[UIScreen mainScreen] nativeBounds].size;
    CGFloat heightInInches = devicePhysicalSize.height / [[UIScreen mainScreen] nativeScale] / 160.0;
    return heightInInches;
}


+ (NSString *)getDeviceLanguage {
    NSArray *languageArray = [NSLocale preferredLanguages];
    return [languageArray objectAtIndex:0];
}

+ (NSDictionary *)getWIFIDict{

    NSArray *interfaces = (__bridge_transfer id)CNCopySupportedInterfaces();
    id info = nil;
    for (NSString *interfaceName in interfaces) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName);
        if (info && [info count]) {
            break;
        }
    }

    if (info) {
        NSDictionary *networkInfo = (NSDictionary *)info;
        return networkInfo;
    }
    return nil;
}

#pragma mark ------uploadDataEmergencyContactInfo-----
+ (void)uploadDataEmergencyContactInfo:(NSMutableArray *)muArr withResult:(VoidBlock)block{
    if (muArr.count == 0) {
        return;
    }
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:muArr options:0 error:&error];
    NSString *base64String = [[jsonData base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSMutableDictionary *muDic = @{
        @"lord":@"3",
        @"warn":@"warnContact",
        @"scraper":@"scraperContact",
        @"clip":base64String,
    }.mutableCopy;
    [HttpNetHelper postNetworkHelperForPath:kUploadContactDataUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            return;
        }
       
        if (block) {
            block();
        }
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        
    } withIsForm:YES];
    
}

#pragma mark ------uploadMaiDianData-----
+ (void)uploadMaiDianData:(NSString *)typeStr withOrderIdStr:(NSString *)orderIdStr withOrderNoStr:(NSString *)orderNoStr withLongitude:(NSString *)longitudeStr withLatitude:(NSString *)latitudeStr withStartTime:(NSString *)startTimeStr withEndTime:(NSString *)endTimeStr{
    NSMutableDictionary *muDic = @{
        @"shellfish":PMStringIsEmpty(orderIdStr) ? @"" : esString(orderIdStr),
        @"passages":PMStringIsEmpty(orderNoStr) ? @"" : esString(orderNoStr),
        @"recruits":esString(typeStr),
        @"quest":esString([IDFVTools getIDFV]),
        @"shores":esString([ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString),
        @"vila":PMStringIsEmpty(longitudeStr) ? @"" : esString(longitudeStr),
        @"santo":PMStringIsEmpty(latitudeStr) ? @"" : esString(latitudeStr),
        @"ply":esString(startTimeStr),
        @"allowing":esString(endTimeStr),
    }.mutableCopy;
    [HttpNetHelper postNetworkHelperForPath:kUploadMaiDianDataUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            return;
        }
        if ([typeStr isEqualToString:@"1"]) {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRecordLoginStartTime];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRecordLoginEndTime];
            [[NSUserDefaults standardUserDefaults] synchronize];
        } 

    } onCompleteFailur:^(NSError * _Nonnull error) {
        
    } withIsForm:YES];
}


@end

